import React from 'react';

function ajax(url) {
  return new Promise(function (resolve) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.responseType = 'json';
    xhr.onload = function () {
      if (this.status === 200) {
        resolve(this.response);
      }
    };
    xhr.send();
  });
}

async function main() {
  const { data: user } = await ajax('http://localhost:3001/api/userData');
  console.log(user);

  const { data: post } = await ajax('http://localhost:3001/api/postData');
  console.log(post);

  const err = await ajax('/api/errData');
  console.log(err);
}

function debounce(fn) {
  let hasClickedRecently = false;

  return function (...args) {
    if (hasClickedRecently) return;
    hasClickedRecently = true;
    const timeID = setTimeout(() => {
      fn.call(this, ...args);
      hasClickedRecently = false;
      clearTimeout(timeID);
    }, 1000);
  };
}

export default function Increase() {
  const fetch = debounce(main);

  return (
    <div>
      <p>函数防抖</p>
      <button type="button" onClick={fetch}>
        点击触发
      </button>
    </div>
  );
}
